const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');
Page({
  data: {
    // 表单数据（所有字段）
    zk_exam_info: {
      // 考生类别 - 增加id和name字段
      candidate_category_id: '',
      candidate_category_code: '',
      candidate_category_name: '',
      
      // 考生类型 - 增加id和name字段
      candidate_type_id: '',
      candidate_type_code: '',
      candidate_type_name: '',
      
      // 报名点 - 增加id和name字段
      registration_site_id: '',
      registration_site_code: '',
      registration_site_name: '',
      
      // 毕业学校 - 增加id和name字段
      graduation_school_id: '',
      graduation_school_code: '',
      graduation_school_name: '',
      
      // 其他输入字段
      schooling_length: '',   // 学制
      mailing_address: '',    // 通讯地址
      postal_code: '',        // 邮政编码
      special_skills: '',      // 特长
      work_school_code: '',   // 工作单位代码
      junior_position: ''     // 职务
    },
    
    // 下拉选项及下标
    candidateCategoryOptions: [],
    candidateCategoryIndex: null,
    
    candidateTypeOptions: [],
    candidateTypeIndex: null,
    
    examSiteOptions: [],
    examSiteIndex: null,
    
    graduationSchoolOptions: [],
    graduationSchoolIndex: null,

    // 语音相关
    recordedText: null,
    recording: false,
    recordFilePath: '',
    buttonText: '开始录音'
  },

  onLoad() {
    this.initForm();
  },
  
  async initForm() {
    try {
      // 1️⃣ 加载下拉框选项（必须 await）
      await this.loadOptions();
  
      // 2️⃣ 再加载本地存储的表单数据
      const storedData = wx.getStorageSync('zk_exam_info');
      if (storedData) {
        this.setData({
          zk_exam_info: storedData,
          // 等 options 全部加载完之后，这里才能找到正确的 index
          candidateCategoryIndex: tools.findIndexByCode(this.data.candidateCategoryOptions, storedData.candidate_category_code),
          candidateTypeIndex: tools.findIndexByCode(this.data.candidateTypeOptions, storedData.candidate_type_code),
          examSiteIndex: tools.findIndexByCode(this.data.examSiteOptions, storedData.registration_site_code),
          graduationSchoolIndex: tools.findIndexByCode(this.data.graduationSchoolOptions, storedData.graduation_school_code)
        });
      }
    } catch (err) {
      console.error("初始化表单失败：", err);
    }
  },

  // 加载所有下拉选项
  async loadOptions() {
    try {
      // 同时加载所有选项
      const categoryPromise = tools.fetchOptions('/zhongkao/category/all', 'candidateCategoryOptions',this);
      const typePromise = tools.fetchOptions('/zhongkao/candidateType/all', 'candidateTypeOptions',this);
      const sitePromise = tools.fetchOptions('/zhongkao/registrationSite/all', 'examSiteOptions',this);
      const schoolPromise = tools.fetchOptions('/zhongkao/graduationSchool/all', 'graduationSchoolOptions',this);
      
      await Promise.all([categoryPromise, typePromise, sitePromise, schoolPromise]);
      
      // 加载完成后更新索引和ID/NAME
      this.updateIdAndNameFromCode();
    } catch (err) {
      console.error('加载选项失败:', err);
    }
  },
  
  // 根据当前code值更新对应的id和name
  updateIdAndNameFromCode() {
    const info = this.data.zk_exam_info;
    const updateData = {};
    
    // 更新考生类别
    if (info.candidate_category_code) {
      const category = this.data.candidateCategoryOptions.find(
        opt => opt.code == info.candidate_category_code
      );
      if (category) {
        updateData['zk_exam_info.candidate_category_id'] = category.id;
        updateData['zk_exam_info.candidate_category_name'] = category.name;
      }
    }
    
    // 更新考生类型
    if (info.candidate_type_code) {
      const type = this.data.candidateTypeOptions.find(
        opt => opt.code == info.candidate_type_code
      );
      if (type) {
        updateData['zk_exam_info.candidate_type_id'] = type.id;
        updateData['zk_exam_info.candidate_type_name'] = type.name;
      }
    }
    
    // 更新报名点
    if (info.registration_site_code) {
      const site = this.data.examSiteOptions.find(
        opt => opt.code == info.registration_site_code
      );
      if (site) {
        updateData['zk_exam_info.registration_site_id'] = site.id;
        updateData['zk_exam_info.registration_site_name'] = site.name;
      }
    }
    
    // 更新毕业学校
    if (info.graduation_school_code) {
      const school = this.data.graduationSchoolOptions.find(
        opt => opt.code == info.graduation_school_code
      );
      if (school) {
        updateData['zk_exam_info.graduation_school_id'] = school.id;
        updateData['zk_exam_info.graduation_school_name'] = school.name;
      }
    }
    
    // 如果有更新，则设置数据
    if (Object.keys(updateData).length > 0) {
      this.setData(updateData);
    }
  },


  // 下拉选择回调 - 同时保存id, code和name
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    let optionKey = '';
    
    if (field === 'candidate_category_code') {
      optionKey = 'candidateCategoryOptions';
      const selected = this.data[optionKey][index];
      this.setData({ 
        candidateCategoryIndex: index,
        'zk_exam_info.candidate_category_id': selected.id,
        'zk_exam_info.candidate_category_code': selected.code,
        'zk_exam_info.candidate_category_name': selected.name
      });
    } 
    else if (field === 'candidate_type_code') {
      optionKey = 'candidateTypeOptions';
      const selected = this.data[optionKey][index];
      this.setData({ 
        candidateTypeIndex: index,
        'zk_exam_info.candidate_type_id': selected.id,
        'zk_exam_info.candidate_type_code': selected.code,
        'zk_exam_info.candidate_type_name': selected.name
      });
    } 
    else if (field === 'registration_site_code') {
      optionKey = 'examSiteOptions';
      const selected = this.data[optionKey][index];
      this.setData({ 
        examSiteIndex: index,
        'zk_exam_info.registration_site_id': selected.id,
        'zk_exam_info.registration_site_code': selected.code,
        'zk_exam_info.registration_site_name': selected.name
      });
    } 
    else if (field === 'graduation_school_code') {
      optionKey = 'graduationSchoolOptions';
      const selected = this.data[optionKey][index];
      this.setData({ 
        graduationSchoolIndex: index,
        'zk_exam_info.graduation_school_id': selected.id,
        'zk_exam_info.graduation_school_code': selected.code,
        'zk_exam_info.graduation_school_name': selected.name
      });
    }
  },

  // 处理输入框输入
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`zk_exam_info.${field}`]: value
    });
  },

  // 提交表单
  handleSubmit() {
    // 检查字段是否发生修改
    const fieldsToCheck = [
      'candidate_category_code',  // 考生类别代码
      'candidate_type_code',      // 考生类型代码
      'registration_site_code',   // 报名点代码
      'graduation_school_code',   // 毕业院校代码
      'schooling_length',         // 学制
      'mailing_address',          // 通信地址
      'postal_code',              // 邮政编码
      'special_skills',           // 特长
      'work_school_code',         // 工作单位或学校代码
      'junior_position'           // 初级职务
    ];
    if(tools.checkDataChanged(this.data.zk_exam_info,wx.getStorageSync('zk_exam_info'),fieldsToCheck)){
      const idNumber = wx.getStorageSync('base_candidate_info').id_number;
      // 创建提交对象 - 只包含需要的字段
      const submitData = {
        idNumber:idNumber,
        // 四个下拉框字段的code
        candidateCategoryCode: this.data.zk_exam_info.candidate_category_code,
        candidateTypeCode: this.data.zk_exam_info.candidate_type_code,
        registrationSiteCode: this.data.zk_exam_info.registration_site_code,
        graduationSchoolCode: this.data.zk_exam_info.graduation_school_code,
  
        // 其他输入字段
        schoolingLength: this.data.zk_exam_info.schooling_length,
        mailingAddress: this.data.zk_exam_info.mailing_address,
        postalCode: this.data.zk_exam_info.postal_code,
        specialSkills: this.data.zk_exam_info.special_skills,
        workSchoolCode: this.data.zk_exam_info.work_school_code,
        juniorPosition: this.data.zk_exam_info.junior_position
      };
      // 提交到后端（只提交code）
      http.post("/zhongkao/registrations/upsert", submitData).then(res => {
        if (res.data.code === 200) {
          // 保存完整数据到本地存储（包含id, code, name）
          wx.setStorageSync('zk_exam_info', this.data.zk_exam_info);
          wx.showToast({ title: '报名信息保存成功', duration: 2000 });
          // 跳转页面
          wx.reLaunch({
            url: '/pages/zhongkao/zk_exam_registrationInfo/zk_exam_registrationInfo',
          })
        }
      }).catch(err => {
        console.error('保存失败:', err);
        wx.showToast({ title: '保存失败', icon: 'none', duration: 2000 });
    });
    }else{
      wx.reLaunch({
        url: '/pages/zhongkao/zk_exam_registrationInfo/zk_exam_registrationInfo',
      })
    }
  },

  // 语音功能
  // 录音功能区
  /**
   * 切换录音状态（开始/停止录音）
   */
  toggleRecording() {
    if (this.data.recording) {
      this.setData({ recording: false });
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
      recorderManager.onStop((res) => {
      wx.setStorageSync('recordPath', res.tempFilePath);
      this.setData({ recordFilePath: res.tempFilePath });
      this.setData({ buttonText: '开始录音' });
      });
    } else {
      tools.checkRecordPermission().then(()=>{
        this.setData({ recording: true, buttonText: '停止录音' });
        // 开始录音
        const recorderManager = wx.getRecorderManager();
        recorderManager.start({
          format: 'wav',
          duration: 60000,
          sampleRate: 44100,
          numberOfChannels: 1,
          encodeBitRate: 96000
        });
      })
      .catch((err) => {
        wx.showToast({ title: err.message, icon: 'none' });
      });
    }
  },

  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
      wx.showToast({ title: '请先录制录音', icon: 'none' });
      return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.zkExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
      this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },

  // 获取了语音识别返回的结果后，对id和index进行更新
  updateIdAndIndex(dataFields){
    // 可以直接赋值的字段
    const fields = ['schooling_length', 'mailing_address', 'postal_code', 'special_skills', 'work_school_code', 'junior_position'];

    // 需要进行映射的字段
    // 名称和id的映射,key为code字段，value为name字段
    const idFields={
      candidate_category_code: 'candidate_category',
      candidate_type_code: 'candidate_type',
      registration_site_code: 'registration_site',
      graduation_school_code: 'graduation_school'
    }
    // 名称和选项映射的字段
    const arrayFields = {
      // 考试相关选项字段
      candidate_category_code: 'candidateCategoryOptions',
      candidate_type_code: 'candidateTypeOptions',
      registration_site_code: 'examSiteOptions',
      graduation_school_code: 'graduationSchoolOptions'
    }
    // 根据结果给字段直接赋值
    fields.forEach(key =>{
      console.log("fields:"," key:",key," value:",dataFields[key])
      if(typeof dataFields[key] === 'string' && !dataFields[key].includes("未知")){
          this.setData({
              [`gk_exam_info.${key}`]:dataFields[key]
          })
      }
    })
    // 根据名字赋值code
    Object.entries(idFields).forEach(([key,value]) =>{
      console.log("idFields:"," key:",key," value:",dataFields[value])
      // 通过两个字典的映射获取对应的值，查询id随后进行赋值
      if(typeof dataFields[value] === 'string' && !dataFields[value].includes("未知")){
        this.setData({
          [`gk_exam_info.${key}`]: tools.findCodeByName(this.data[arrayFields[key]], dataFields[value])
        })
      }
    })
    //更新下标
    this.updateIndexIdName(this.data.zk_exam_info)
  },
  updateIndexIdName(data){
    // 根据当前信息更新下标
    this.setData({
      candidateCategoryIndex: tools.findIndexByCode(this.data.candidateCategoryOptions, data.candidate_category_code),
      candidateTypeIndex: tools.findIndexByCode(this.data.candidateTypeOptions, data.candidate_type_code),
      examSiteIndex: tools.findIndexByCode(this.data.examSiteOptions, data.registration_site_code),
      graduationSchoolIndex: tools.findIndexByCode(this.data.graduationSchoolOptions, data.graduation_school_code)
    })
    // 更新id和name信息
    this.updateIdAndNameFromCode()
  }
});